package com.dhcc.core.api.auth.impl;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.webservice.SoapClient;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dhcc.core.api.auth.IUserAuth;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.security.client.form.Encrypt;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.cache.config.IConfigCache;
import com.dhcc.core.modules.system.cache.user.UserCache;
import com.dhcc.core.modules.system.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;

@Component("userAuth")
@ConditionalOnProperty(prefix = "sys", name = "authType", havingValue = "portal")
public class PortalAuthImpl implements IUserAuth {

    @Autowired
    private IConfigCache configCache;

    @Override
    public R doAuth(String loginName, String password) {
        // 获取portal登录验证的url和方法
        String url = configCache.getValueByKey("portal.auth.url");
        String method = configCache.getValueByKey("portal.auth.method");

        // 对密码进行加密处理（移动端前端无法加密，因为前端加密用到了jquery，移动端使用的vue.js，不支持jquery）
        password = Encrypt.dhc_cacheEncrypt(password);

        password = StringUtils.replaceAll(password, "<", "&lt;");
        password = StringUtils.replaceAll(password, ">", "&gt;");
        password = StringUtils.replaceAll(password, "&", "&amp;");

        StringBuilder request = new StringBuilder();
        request.append("<request>");
        request.append("<hospital>");
        request.append("CSYY001");
        request.append("</hospital>");
        request.append("<userCode>");
        request.append(loginName);
        request.append("</userCode>");
        request.append("<password>");
        request.append(password);
        request.append("</password>");
        request.append("</request>");

        // 新建客户端，设置要请求的方法、传入对应的命名空间、设置参数
        SoapClient client = SoapClient.create(url).setMethod(method, "http://service.sync.user.common.dhcc.com").setParam("data", request.toString());
        Document document = XmlUtil.parseXml(client.send(true));
        String response = document.getElementsByTagName("ns:return").item(0).getFirstChild().getNodeValue();
        JSONObject responseObj = JSONUtil.xmlToJson(response);
        String status = responseObj.getJSONObject("response").getStr("status");
        if (CommonUtil.equals(status, "1")) {
            // portal认证成功，需要判断OA中是否存在此用户
            User user = UserCache.me().getUserByLoginName(loginName);
            if (CommonUtil.isNotEmpty(user)) {
                return R.ok();
            } else {
                return R.error("OA中没有工号为：" + loginName + "的用户!");
            }
        } else {
            return R.error(responseObj.getJSONObject("response").getStr("errMSG"));
        }
    }

}
